/*!
 * Ext JS Library 3.1.1
 * Copyright(c) 2006-2010 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
var UI = function (){
	var currentfolderid="1";//需改进，根目录id不一定总是1
	var store;
	var grid;
	var createFolderDialog;
	return {
    init : function() {
      //we enable the QuickTips for the later Pagebar
      Ext.QuickTips.init(); 
	  Ext.BLANK_IMAGE_URL = '../../resources/ext3/resources/images/default/s.gif';
      initDataSource();
      buildUI();
    }   
	};
	
	function initDataSource() {

		 // create the Data Store
    store = new Ext.data.JsonStore({
        root: 'list',
        totalProperty: 'totalSize',
        idProperty: 'id',
        remoteSort: true,

        fields: [
            'id', 'filename', 'filesize', 'creatorname','createtime','fileicon','objkey',
			'updatetime','version','state','style','annexid'
        ],

        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
            url: '../dms.do?method=list'
        })
    });
    store.setDefaultSort('id', 'desc');
	
	}
   
	function buildUI() {

    // pluggable renders
    function renderTopic(value, p, record){
        return String.format(
                '<b><a href="http://extjs.com/forum/showthread.php?t={2}" target="_blank">{0}</a></b><a href="http://extjs.com/forum/forumdisplay.php?f={3}" target="_blank">{1} Forum</a>',
                value, record.data.forumtitle, record.id, record.data.forumid);
    }
    function renderLast(value, p, r){
        return String.format('{0}<br/>by {1}', value.dateFormat('M j, Y, g:i a'), r.data['lastposter']);
    }
	function AddImgs(value,p,record){
        //if(record.data.descrip != "")
        //{
        //    p.attr='ext:qtip="Add to playlist" style="background-image:url(../../resources/images/attach/other.gif) !important; background-position: center 2px; background-repeat: no-repeat;cursor: pointer;"';
        // }
				
		if ( record.data.objkey == 'FOLDER') 
		{ 
		return "<img src='../../resources/images/attach/folder.png'  style='margin-bottom:-3px'/>&nbsp;<span>"+value+"</span>"; 
		} else if ( record.data.style == 'txt') { 
		return "<img src='../../resources/images/attach/txt.gif'  style='margin-bottom:-3px'/>&nbsp;<span>"+value+"</span>";  
		}  else if ( record.data.style == 'pdf') { 
		return "<img src='../../resources/images/attach/pdf.gif' style='margin-bottom:-3px' />&nbsp;<span>"+value+"</span>"; 
		}  else if ( record.data.style == 'doc') { 
		return "<img src='../../resources/images/attach/word.gif' style='margin-bottom:-3px'/>&nbsp;<span>"+value+"</span>"; 
		}  else if ( record.data.style == 'zip') { 
		return "<img src='../../resources/images/attach/zip.gif'  style='margin-bottom:-3px'/>&nbsp;<span>"+value+"</span>";  
		}  else if ( record.data.style == 'ppt') { 
		return "<img src='../../resources/images/attach/ppt.gif'  style='margin-bottom:-3px'/>&nbsp;<span>"+value+"</span>";  
		} else{ 
		return "<img src='../../resources/images/attach/other.gif' style='margin-bottom:-3px' />&nbsp;<span>"+value+"</span>";  
		} 

	}



	var tb = new Ext.Toolbar( [{
        text: '新建文件夹',
        cls: 'x-btn-text-icon',
        icon: 'js/104.gif',
        handler: function(){
            showCreateFolderDialog();
        }
    },{
        text: '新建文档',
        cls: 'x-btn-text-icon',
        icon: 'js/289.gif',
        handler : function(){
          doAddNewFile();
        }
    }]);

    grid = new Ext.grid.GridPanel({
        width:700,
        height:300,
        //title:'ExtJS.com - Browse Forums',
        store: store,
        trackMouseOver:true,
        //disableSelection:true,
		singleSelect:true,
		stripeRows: true,
		autoExpandColumn:'filename',
        loadMask: true,
		tbar: tb,
        // grid columns
        columns:[{
            id: 'id', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: "id",
            dataIndex: 'id',
            width: 420,
            //renderer: renderTopic,
			hidden: true,
            sortable: true
        },{
            header: "style",
            dataIndex: 'style',
            hidden: true
        },{
            header: "objkey",
            dataIndex: 'objkey',
            hidden: true
        },{
            header: "状态",
            dataIndex: 'state',
            width: 50
        },{ id: 'filename',
            header: "文档名称",
            dataIndex: 'filename',
            renderer:AddImgs.createDelegate(this),
            sortable: true
        },{
            header: "版本",
            dataIndex: 'version',
            width: 50,
            align: 'right',
            sortable: true
        },{
            header: "文件大小",
            dataIndex: 'filesize',
            width: 70,
            align: 'right',
            sortable: true
        },{
            header: "创建者",
            dataIndex: 'creatorname',
            width: 100,
            //renderer: renderLast,
            sortable: true
        },{
            header: "创建时间",
            dataIndex: 'createtime',
            width: 100,
            //renderer: renderLast,
            sortable: true
        }],

        // customize view config
       /* viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true,
            getRowClass : function(record, rowIndex, p, store){
                if(this.showPreview){
                    p.body = '<p>'+record.data.excerpt+'</p>';
                    return 'x-grid3-row-expanded';
                }
                return 'x-grid3-row-collapsed';
            }
        },*/

        // paging bar on the bottom
        bbar: new Ext.PagingToolbar({
            pageSize: 25,
            store: store,
            displayInfo: true,
            displayMsg: 'Displaying topics {0} - {1} of {2}',
            emptyMsg: "No topics to display"/*,
            items:[
                '-', {
                pressed: true,
                enableToggle:true,
                text: 'Show Preview',
                cls: 'x-btn-text-icon details',
                toggleHandler: function(btn, pressed){
                    var view = grid.getView();
                    view.showPreview = pressed;
                    view.refresh();
					alert(store.getTotalCount());
                }
            }]*/
        })
    });

	var onRowDoubleClick = function(grid, rowIndex, e){
    var selectionModel = grid.getSelectionModel();     
	var record = selectionModel.getSelected();
	var objkey = record.data.objkey;
	
	if(objkey=="FILEINFO"){
		alert("this is a document");
	}else{
	currentfolderid = record.data['id'];
	store.load({params:{start:0, limit:20,folderid:currentfolderid}}); 
	
	}
	
    }
	grid.addListener('rowdblclick', onRowDoubleClick);

    // render it
    grid.render('topic-grid');

    // trigger the data store load
    store.load({params:{start:0, limit:20}});
	}


   /************************************************************
   * 建立新的文件夹
   *   显示新建文件夹对话框，完成文件夹建立功能
   ************************************************************/ 
  function showCreateFolderDialog() {
    if(!createFolderDialog) {
      createFolderDialog = new function(){
		
        var resourceDialog; //显示的对话框
        var tabs;
  
	// A new generic text field
		var textField =  new Ext.form.TextField();

		var tabs = new Ext.FormPanel({
        labelWidth: 50,
        border:false,
        width: 350,
		/*submit: function(){
					
                    tabs.getForm().getEl().dom.action = '../app/dms.do?method=save',
                    tabs.getForm().getEl().dom.method='POST',
                    tabs.getForm().getEl().dom.submit();
					 
              },*/
        items: {
            //xtype:'tabpanel',
            activeTab: 0,
            defaults:{autoHeight:true, bodyStyle:'padding:2px'}, 
            items:[{
                title:'新建文件夹',
                layout:'form',
                defaults: {width: 200},
                defaultType: 'textfield',

                items: [{
                    fieldLabel: '名称',
                    name: 'COL_FOLDERNAME',
                    value: ''
                }]
            }
			]
        }

    });

         
        resourceDialog =  new Ext.Window({
            el: 'create-resource-dlg',
            layout: 'fit',
            width:360,
            height:260,
            resizable: false,
            //title: '新建文件夹',
            //border:false,
            closeAction:'hide',
            plain:true,
            modal: true,
            items: [tabs],
            buttons: [{
                text: '确定',
                handler: doAddAction
            },{
                text: '重输',
                handler: resetForm
            },{
                text: '取消',
                handler: function() {
                  resourceDialog.hide();
                }
            }]            
        });
        //资源信息保存操作
        function doAddAction() {
          if(!tabs.getForm().isValid()) {
             Ext.MessageBox.alert('错误', '请修正非法数据后再保存！');
          } else {
			tabs.getForm()
            tabs.getForm().submit(
			{url:'../dms.do?method=save',
			 waitMsg:'提交处理过程中...',
			 method:'POST',/**/
			 params:{COL_FOLDERICON:'FOLDER',COL_PARENTFOLDERID:currentfolderid,objkey:'FOLDER',okey:'FOLDER'},
			 success:function(form,action){
			 Ext.Msg.alert('提示', '保存成功'); 
			 form.responseText; //返回的结果
			},
			  failure: function(){
			  Ext.Msg.alert('提示','处理出现异常');
			  }
			  }	
			);
			store.reload();
			resourceDialog.hide();
          } 
        }
        
        function doAddResp(ret) {
          Ext.MessageBox.alert('操作结束', '保存成功！');
          tabs.hide();
          store.reload();
        }     
        
        //重置输入框内容        
        function resetForm() {
        }
        
        //向外公开的方法
        this.show = function() {
          //resetForm();
          resourceDialog.show();
        }
		
      }();
    }
    createFolderDialog.show();
  }


}();
//Ext.onReady(UI.init, UI);
